package com.ljxt.dt.web.servlet.purchasingmanagementservlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljxt.dt.dao.purchasingmanagementdao.impl.PurchaseInfoDaoImpl;
import com.ljxt.dt.domain.HandlerInfo;
import com.ljxt.dt.domain.PurchaseDetail;
import com.ljxt.dt.service.purchasingmanagementservice.PurchaseDetailService;
import com.ljxt.dt.service.purchasingmanagementservice.PurchaseInfoService;
import com.ljxt.dt.service.purchasingmanagementservice.impl.PurchaseDetailServiceImpl;
import com.ljxt.dt.service.purchasingmanagementservice.impl.PurchaseInfoServiceImpl;
import com.ljxt.dt.util.xhq.ClassUtil;
import com.ljxt.dt.util.xhq.RequestUtil;
import com.ljxt.dt.util.xhq.StringUtil;
import com.ljxt.dt.util.xhq.test.ContinuousTableMapping;
import com.ljxt.dt.vo.JsonResult;
import com.ljxt.dt.vo.purchasingmanagement.CgddHandlerInfo;
import com.ljxt.dt.vo.purchasingmanagement.PurchaseDetailTableVO;
import com.ljxt.dt.vo.purchasingmanagement.PurchaseMainVo;
import com.ljxt.dt.vo.storemanagement.GoodsDate;
import com.ljxt.dt.vo.storemanagement.JsonBen;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @author 徐浩钦
 * @version 1.0.0
 * @date 2020/5/15 20:22
 * @copyright 老九学堂T11
 */
@WebServlet("/cgddDetail.html")
public class CgddDetailServlet extends HttpServlet {
    private static PurchaseInfoService purchaseInfoService = new PurchaseInfoServiceImpl();
    private static PurchaseDetailService purchaseDetailService = new PurchaseDetailServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("CgddDetailServlet -> doGet");

        String reqType = req.getParameter("reqType");
        reqType = StringUtil.isNullAndEmpty(reqType) ? "编辑" : reqType;
        switch (reqType){
            case "编辑":
                break;
            case "审核":
                break;
            case "确认":
                break;
            default:
                break;
        }

        // 传入 采购订单的主编号
        PurchaseMainVo purchaseMainVo = RequestUtil.reqToObj(req,PurchaseMainVo.class);

        // 设置对应的供应商和采购明细数据
        purchaseMainVo.setSupplier(purchaseDetailService.selectSupplierInfoByPurchaseId(purchaseMainVo.getOrderNo()));
        purchaseMainVo.setGoodsInfos(purchaseDetailService.selectGoodsByPurchaseId(purchaseMainVo.getOrderNo()));

        // 根据采购订单获取对应的采购流程信息
        List<CgddHandlerInfo> cgddHandlerInfos = purchaseInfoService.selectHandlerByCgddId(purchaseMainVo.getOrderNo());
        System.out.println(cgddHandlerInfos);

        // 这个根据明细里的采购 id 进行后台的连表查询得到一个属性结构的结果集
        ContinuousTableMapping continuousTableMapping = new PurchaseInfoDaoImpl().select(purchaseMainVo.getOrderNo());

        // 答应该旗下的所有商品
        req.setAttribute("data",purchaseMainVo);


        //  用来存储商品id 和他在某个明细中所有商品属性的映射集合
        LinkedHashMap<String,ArrayList<Map<String,String>>> map = new LinkedHashMap<>();
        Map<String,Map<String,String>> mapMap = new HashMap<>();

        // 用来存储表格的列，按照顺序进行了添加
        List<String> cols = new ArrayList<>();
        // 用来存储表格的行数据
        List<Map<String,Object>> rows = new ArrayList<>();

        // 组装显示的列头名称
        cols.add("编号");
        cols.add("物品展示");
        cols.add("采购物品");
        cols.add("物品ID");
        cols.add("计量单位");
        cols.add("商品总数");
        cols.add("金额小计(元)");


        Map<String,List<PurchaseDetailTableVO>> voMap = new HashMap<>();
        Map<String,Object> sumVo = new HashMap<>();
        int wpzl = 0;
        int wpzs = 0;
        double cbzj = 0d;

        // 所有的结果集合
        ArrayList<LinkedHashMap<String, Object>> arrayList = continuousTableMapping.getContent();
        // 循环遍历结果
        for (int i = 0; i < arrayList.size(); i++) {

            // row 是前端每行需要显示的键值对
            Map<String,Object> row = new LinkedHashMap<>();
            // 这个是每个结果的值映射，方便使用
            LinkedHashMap<String, Object> hashMap = arrayList.get(i);
            // child 是每个结果对应的子查询的节点
            ContinuousTableMapping child = continuousTableMapping.getChildLists().get(i);

            row.put("bh",i);
            row.put("cgwp",child.getContent().get(0).get("cgwp"));
            row.put("picture",child.getContent().get(0).get("picture"));
            row.put("wpid",child.getContent().get(0).get("spid"));
            row.put("jldw",child.getContent().get(0).get("jldw"));
            row.put("tjsl",hashMap.get("tjsl").toString());
            row.put("jexj",hashMap.get("jexj").toString());
            rows.add(row);

            // 统计的计算
            wpzl++;
            wpzs+=Integer.parseInt(hashMap.get("tjsl").toString());
            cbzj+= Double.parseDouble(hashMap.get("jexj").toString());


            // 获取到每个循环时他们对应的二级结果内容，
            // 因为同一个明细表中可能存在同一个商品有不同属性的相同商品，所以进行遍历
            ArrayList<LinkedHashMap<String, Object>> contents = child.getContent();
            for (LinkedHashMap<String, Object> content : contents) {
                // 取出需要的商品属性 和 商品id 用于后面进行绑定
                String spsx = content.get("spsx").toString();
                String spid = content.get("spid").toString();


                // 获取采购数量和采购单价
                String cgsl = content.get("cgsl").toString();
                String cgdj = content.get("cgdj").toString();



                if(voMap.get("WP"+spid) == null){
                    voMap.put("WP"+spid,new ArrayList<>());
                }

                // 判断该商品是否存在过，如果不存在则实例化一个存储
                // 存在的后续通过值的 list 进行 add 即可
                if(map.get(spid) == null){
                    map.put(spid,new ArrayList<>());
                }

                // 判断商品属性是否为空的，有的商品是没有属性的，没有则跳过
                if (spsx.isEmpty()){
                    PurchaseDetailTableVO purchaseDetailTableVO1 = new PurchaseDetailTableVO();
                    purchaseDetailTableVO1.setSpdj(cgdj);
                    purchaseDetailTableVO1.setSpsl(cgsl);
                    voMap.get("WP"+spid).add(purchaseDetailTableVO1);
                    continue;
                }

                /**
                 * 使用逗号和恒杠对字符串描述进行拆分
                 * 然后存储在 map 中，传入到后台去查询
                 * 最后将结果存储在 循环外部的 map 中
                 */
                Map<String,String> tempAttrMap = new HashMap<>();
                String[] strings = spsx.split(",");
                for (String string : strings) {
                    String[] split = string.split("-");
                    String s = split[0];
                    String v = split[1];
                    tempAttrMap.put(s,v);
                }
                // 将结果 add 进去
                Map<String, String> resMap = purchaseInfoService.selectAttrAndCategory(tempAttrMap);
                map.get(spid).add(resMap);

                // 设置属性的明细
                PurchaseDetailTableVO purchaseDetailTableVO = new PurchaseDetailTableVO();
                purchaseDetailTableVO.setSpdj(cgdj);
                purchaseDetailTableVO.setSpsl(cgsl);
                purchaseDetailTableVO.setSpsx(resMap);
                purchaseDetailTableVO.setSpid(spid);
                voMap.get("WP"+spid).add(purchaseDetailTableVO);
            }
        }

        System.out.println("mapmapmap---");
        System.out.println(cols);
        System.out.println(rows);
        System.out.println(map);
        System.out.println(voMap);

        // 这是统计的数据 物品种类 物品总数 成本总计
        req.setAttribute("wpzl",wpzl);
        req.setAttribute("wpzs",wpzs);
        req.setAttribute("cbzj",cbzj);

        System.out.println(rows);
        // 列名
        req.setAttribute("tableColumn",cols);
        // 行
        req.setAttribute("tableRow",rows);
        // 详细属性
        req.setAttribute("tableRowInfo",voMap);
        // 统计
        req.setAttribute("sumNumber",voMap);

        LinkedHashMap<String,String> map1 = new LinkedHashMap<>();
        map1.put("typeName","流程名称");
        map1.put("name","经办人");
        map1.put("result","结果");
        map1.put("strTime","提交时间");
        map1.put("remark","备注");

        Map<String,Object> cgddTable = new HashMap<>();

        // 将对象转换为 list 装 map 的集合

        ArrayList<LinkedHashMap<String, Object>> arrayLists = ClassUtil.listObjsToMapByMap(cgddHandlerInfos, map1);
        // 获取这个集合的所有对象进行遍历
        System.out.println(map1);
        System.out.println(arrayLists);
        System.out.println(cgddHandlerInfos);

        cgddTable.put("cols", map1);
        cgddTable.put("rows", arrayLists);

        req.setAttribute("cgddTable",
                cgddTable);
        req.setAttribute("orderNo",purchaseMainVo.getOrderNo());


        req.getRequestDispatcher("WEB-INF/views/purchasingManagement/cgddDetail.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入了 CgddDetailServlet -> post");
        // 获取采购订单 id ，提交的方式，结果的选择，填写的备注
        String orderNo = req.getParameter("ordId");
        String reqType = req.getParameter("reqType");
        String result = req.getParameter("result");
        String remark = req.getParameter("remark");
        String name = req.getParameter("name");

        HandlerInfo handlerInfo = new HandlerInfo();
        handlerInfo.setTime(new Date());
        handlerInfo.setRemarks(remark);
        handlerInfo.setName(name);
        handlerInfo.setResultId(Integer.parseInt(result));
        handlerInfo.sethandlerTypeId(Integer.parseInt(reqType));
        handlerInfo.setOrderNo(orderNo);

        int i = purchaseInfoService.insertIntoHandlerInfo(handlerInfo);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(orderNo);

        // 修改成功
        if(i > 0){
            jsonResult.setCode("200");
            if("3".equals(reqType) && "4".equals(result)){
                // 如果是确认采购的流程则，根据采购订单的 id 获取到所有的明细表信息
                List<PurchaseDetail> purchaseDetails = purchaseInfoService.selectPurchaseDetailByPurchaseInfo(orderNo);

                JsonBen jsonBen = new JsonBen();
                jsonBen.setTypeId(2);
                jsonBen.setOrderNo(orderNo);
                jsonBen.setRemark(remark);

                List<GoodsDate> list = new ArrayList<>();
                for (PurchaseDetail purchaseDetail : purchaseDetails) {
                    GoodsDate goodsDate = new GoodsDate();
                    goodsDate.setAttrId(purchaseDetail.getAttrId());
                    goodsDate.setGoodsId(purchaseDetail.getGoodsId());
                    goodsDate.setReceptAmount(purchaseDetail.getQuantity());
                    list.add(goodsDate);
                }
                jsonBen.setGoodsInfoDate(list);

                jsonResult.setData(jsonBen);
            }
        }else {
            jsonResult.setCode("500");
        }

        resp.getWriter().write(new ObjectMapper().writeValueAsString(jsonResult));
    }
}
